<template>
  <div class="posts-container">
    <!-- 搜索表单 -->
    <div class="mb10">
      <SearchForm :searchFields="searchItems" :maxFirstRowItems="3" @search="handleSearch" @reset="handleReset" />
    </div>

    <!-- 操作按钮 -->
    <div class="mb10">
      <div class="table-operations">
        <a-button type="primary" danger :disabled="!hasSelected" @click="handleBatchDelete">
          <DeleteOutlined /> 批量删除
        </a-button>
        <span style="margin-left: 8px;" v-if="hasSelected">
          已选择 {{ selectedRowKeys.length }} 项
        </span>
      </div>
    </div>

    <!-- 数据列表 -->
    <div class="card-wrap">
      <DataList ref="dataListRef" :api="(params) => postApi.getListByPage(params)" :deleteApi="postApi.deletePost"
        :columns="columns" :rowSelection="rowSelection" @action="onAction">
        <!-- 自定义列插槽 -->

        <template #content="{ record }">
          <div class="post-content-wrapper">
            <div class="post-text">
              {{ record.content ? record.content.substring(0, 100) + (record.content.length > 100 ? '...' : '') : '无内容'
              }}
            </div>
            <div v-if="record.media && parseMedia(record.media).length > 0" class="post-images">
              <a-image-preview-group>
                <div class="image-grid">
                  <a-image v-for="(media, index) in parseMedia(record.media).filter(m => m && isImage(m)).slice(0, 9)"
                    :key="`img-${record.id}-${index}`" :src="getImageUrl(media)" :width="60" :height="60"
                    class="grid-image" :style="{ objectFit: 'cover' }" :preview="{
                      src: getImageUrl(media)
                    }" />
                </div>
              </a-image-preview-group>
            </div>
          </div>
        </template>

        <template #user="{ record }">
          <div class="user-info">
            <a-avatar :src="getImageUrl(record.user?.avatar)" size="small">
              {{ record.user?.nickname?.charAt(0) }}
            </a-avatar>
            <div class="user-details">
              <div>{{ record.user?.nickname || '未知用户' }}</div>
            </div>
          </div>
        </template>

        <template #topic="{ record }">
          <div class="topic-info">
            <a-avatar :src="getImageUrl(record.topic?.cover_image)" size="small" shape="square">
              {{ record.topic?.name?.charAt(0) }}
            </a-avatar>
            <div class="topic-details">
              <div class="topic-name">{{ record.topic?.name || '未知圈子' }}</div>
            </div>
          </div>
        </template>

        <template #created_at="{ record }">
          <div>{{ formatDate(record.created_at) }}</div>
        </template>

        <template #action="{ record }">
          <a-space>
            <a-button type="link" size="small" @click="viewDetail(record)">
              查看详情
            </a-button>
            <a-popconfirm title="确定要删除这个帖子吗？" @confirm="handleDelete(record.id)">
              <a-button type="link" size="small" danger>
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </DataList>
    </div>

    <!-- 帖子详情模态框 -->
    <a-modal v-model:open="detailModalVisible" title="帖子详情" width="800px" :footer="null">
      <div v-if="currentPost" class="post-detail">
        <a-descriptions :column="2" bordered>
          <a-descriptions-item label="标题" :span="2">
            {{ currentPost.title }}
          </a-descriptions-item>
          <a-descriptions-item label="内容" :span="2">
            <div class="post-content-detail">{{ currentPost.content }}</div>
          </a-descriptions-item>
          <a-descriptions-item label="类型">
            <a-tag v-if="currentPost.type === 'graphic'" color="blue">图文</a-tag>
            <a-tag v-else-if="currentPost.type === 'video'" color="orange">视频</a-tag>
            <a-tag v-else-if="currentPost.type === 'vote'" color="purple">投票</a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="发布者">
            {{ currentPost.user?.nickname || '未知用户' }}
          </a-descriptions-item>
          <a-descriptions-item label="所属圈子">
            {{ currentPost.topic?.name || '未知圈子' }}
          </a-descriptions-item>
          <a-descriptions-item label="地址">
            {{ currentPost.address || '无' }}
          </a-descriptions-item>
          <a-descriptions-item label="浏览数">
            {{ currentPost.see_num }}
          </a-descriptions-item>
          <a-descriptions-item label="点赞数">
            {{ currentPost.thumb_num }}
          </a-descriptions-item>
          <a-descriptions-item label="收藏数">
            {{ currentPost.collect_num }}
          </a-descriptions-item>
          <a-descriptions-item label="评论数">
            {{ currentPost.comment_num }}
          </a-descriptions-item>
          <a-descriptions-item label="创建时间">
            {{ formatDate(currentPost.created_at) }}
          </a-descriptions-item>
          <a-descriptions-item label="更新时间">
            {{ formatDate(currentPost.updated_at) }}
          </a-descriptions-item>
        </a-descriptions>

        <!-- 媒体文件展示 -->
        <div v-if="currentPost.media" class="media-section" style="margin-top: 16px;">
          <h4>媒体文件</h4>
          <div class="media-list">
            <div v-for="(media, index) in parseMedia(currentPost.media)" :key="index" class="media-item">
              <img v-if="isImage(media)" :src="getImageUrl(media)" alt="图片"
                style="max-width: 200px; max-height: 200px;" />
              <video v-else-if="isVideo(media)" :src="getImageUrl(media)" controls
                style="max-width: 200px; max-height: 200px;"></video>
              <a v-else :href="getImageUrl(media)" target="_blank">{{ media }}</a>
            </div>
          </div>
        </div>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import { DeleteOutlined } from '@ant-design/icons-vue'
import DataList from '@/components/DataList.vue'
import SearchForm from '@/components/SearchForm.vue'
import { postApi } from '@/api/content'
import { formatDate } from '@/utils/date'
import { getImageUrl } from '@/utils/utils'

// 响应式数据
const dataListRef = ref()
const selectedRowKeys = ref([])
const detailModalVisible = ref(false)
const currentPost = ref(null)
const topicOptions = ref([])

// 搜索表单配置
const searchItems = ref([
  {
    label: '标题',
    prop: 'title',
    type: 'input',
    placeholder: '请输入帖子标题'
  },
  {
    label: '创建时间',
    prop: 'date_range',
    type: 'daterange',
    placeholder: ['开始日期', '结束日期']
  }
])

// 表格列配置
const columns = [
  {
    title: '内容',
    dataIndex: 'content',
    width: 200,
    slot: true
  },
  {
    title: '发布者',
    dataIndex: 'user',
    width: 150,
    slot: true
  },
  {
    title: '圈子',
    dataIndex: 'topic',
    width: 200,
    slot: true
  },
  {
    title: '创建时间',
    dataIndex: 'created_at',
    width: 180,
    slot: true,
    sorter: true
  },
  {
    title: '操作',
    key: 'action',
    width: 150,
    type: 'action',
    options: [
      { title: '查看', key: 'view' },
      { title: '删除', key: 'delete', type: 'delete' }
    ]
  }
]

// 行选择配置
const rowSelection = {
  selectedRowKeys: selectedRowKeys,
  onChange: (keys) => {
    selectedRowKeys.value = keys
  }
}

// 计算属性
const hasSelected = computed(() => selectedRowKeys.value.length > 0)

// 方法
const handleSearch = (params) => {
  // 处理日期范围
  if (params.date_range && params.date_range.length === 2) {
    params.start_date = params.date_range[0]
    params.end_date = params.date_range[1]
    delete params.date_range
  }

  dataListRef.value.search(params)
}

const handleReset = () => {
  dataListRef.value.reset()
}

const handleDelete = async (id) => {
  try {
    await postApi.deletePost({ id })
    message.success('删除成功')
    dataListRef.value.refreshData()
  } catch (error) {
    message.error('删除失败：' + error.message)
  }
}

const handleBatchDelete = () => {
  if (selectedRowKeys.value.length === 0) {
    message.warning('请选择要删除的帖子')
    return
  }

  Modal.confirm({
    title: '确认删除',
    content: `确定要删除选中的 ${selectedRowKeys.value.length} 个帖子吗？`,
    onOk: async () => {
      try {
        await postApi.batchDeletePosts({ ids: selectedRowKeys.value })
        message.success('批量删除成功')
        selectedRowKeys.value = []
        dataListRef.value.refreshData()
      } catch (error) {
        message.error('批量删除失败：' + error.message)
      }
    }
  })
}

const viewDetail = async (record) => {
  try {
    console.log('查看帖子详情，ID:', record.id)
    const response = await postApi.getPostDetail({ id: record.id })
    console.log('帖子API响应:', response)

    if (response && response.result) {
      currentPost.value = response.result
      detailModalVisible.value = true
      console.log('设置帖子详情:', currentPost.value)
    } else {
      message.error('获取帖子详情失败：响应数据为空')
    }
  } catch (error) {
    console.error('获取帖子详情错误:', error)
    message.error('获取帖子详情失败：' + error.message)
  }
}

const parseMedia = (mediaStr) => {
  if (!mediaStr || mediaStr === 'null' || mediaStr === 'undefined') return []

  // 如果已经是数组，直接返回
  if (Array.isArray(mediaStr)) {
    return mediaStr.filter(item => item && typeof item === 'string')
  }

  // 尝试解析JSON
  try {
    const parsed = JSON.parse(mediaStr)
    if (Array.isArray(parsed)) {
      return parsed.filter(item => item && typeof item === 'string')
    }
    return []
  } catch {
    // 如果不是JSON，按逗号分割
    if (typeof mediaStr === 'string') {
      return mediaStr.split(',').filter(item => item && item.trim())
    }
    return []
  }
}

const isImage = (url) => {
  return /\.(jpg|jpeg|png|gif|webp)$/i.test(url)
}

const isVideo = (url) => {
  return /\.(mp4|avi|mov|wmv|flv|webm)$/i.test(url)
}



// 操作按钮点击事件
const onAction = (action, record) => {
  if (action.key === 'view') {
    viewDetail(record)
  }
}
</script>

<style scoped>
.posts-container {
  padding: 24px;
}

.post-title {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.title-text {
  font-weight: 500;
  color: #1890ff;
  cursor: pointer;
}

.post-meta {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #666;
}

.meta-item {
  background: #f5f5f5;
  padding: 2px 6px;
  border-radius: 4px;
}

.post-content-wrapper {
  display: flex;
  flex-direction: column;
  gap: 8px;
  max-width: 200px;
}

.post-text {
  color: #666;
  line-height: 1.4;
  word-break: break-all;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.post-images {
  margin-top: 4px;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 2px;
  max-width: 180px;
}

.grid-image {
  object-fit: cover;
  border-radius: 4px;
  cursor: pointer;
  transition: transform 0.2s;
  display: block;
}

/* 确保a-image组件内的img元素不会拉伸变形 */
.grid-image :deep(img) {
  object-fit: cover !important;
  width: 60px !important;
  height: 60px !important;
}

.grid-image :deep(.ant-image) {
  width: 60px !important;
  height: 60px !important;
}

.grid-image :deep(.ant-image-img) {
  object-fit: cover !important;
}

.grid-image:hover {
  transform: scale(1.05);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.user-id {
  font-size: 12px;
  color: #999;
}

.topic-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.topic-details {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.topic-name {
  font-weight: 500;
}

.topic-id {
  font-size: 12px;
  color: #999;
}

.post-content-detail {
  max-height: 200px;
  overflow-y: auto;
  line-height: 1.6;
  white-space: pre-wrap;
}

.media-section {
  border-top: 1px solid #f0f0f0;
  padding-top: 16px;
}

.media-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.media-item {
  border: 1px solid #d9d9d9;
  border-radius: 4px;
  overflow: hidden;
}

.statistics-cards .ant-card {
  text-align: center;
}

.table-operations {
  display: flex;
  align-items: center;
}
</style>